
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    function getxmselectCustomer(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    let salesmanCodeCustomerList = [];
    let salesmanCodeContractList = [];
    let customerTypeDataList = [];
    let deptSalesmanList=[];
    layer.ready(function () {
        //客户类型
        let customerTypeData = getdictionary(6, 27);
        let customerTypeList = [];
        for(let i in customerTypeData){
            let customerTypeTemp = {
                name: customerTypeData[i].name,
                value: customerTypeData[i].code
            }
            customerTypeList.push(customerTypeTemp);
        }
        customerTypeDataList = getxmselectCustomer("#customerType", "customerType", customerTypeList);


        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            salesmanCodeCustomerList = getxmselect("#salesmanCodeCustomer", "salesmanCodeCustomer", userTree);
            salesmanCodeContractList = getxmselect("#salesmanCodeContract", "salesmanCodeContract", userTree);
        } else {
            salesmanCodeCustomerList = getxmselect("#salesmanCodeCustomer", "salesmanCodeCustomer", [{name: user.name, value: user.code}])
            salesmanCodeContractList = getxmselect("#salesmanCodeContract", "salesmanCodeContract", [{name: user.name, value: user.code}]);
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
        } else {
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }


    });
    form.render();//表单刷新

    table.render({
        elem: '#offerselect'
        , where: {salesmanCodeContract: user.code}
        , url: 'exportContract/statistics/getContractCustomerInfoByPage'
        , toolbar: '#offertoolbar'
        , cols: [[
            //以外销合同主表为主
            {field: 'customerCode', title: '客户编码', sort: true, width: 300, event: "quotationno", align: 'center'}
            , {field: 'customerName', title: '客户名称', sort: true, width: 300, align: 'center'}
            , {field: 'sourceOfCustomers', title: '客户来源', sort: true, width: 300, align: 'center'}
            , {field: 'createDate', title: '客户创建日期', sort: true, width: 300, align: 'center'}
            , {field: 'salesmanNameCustomer', title: '客户业务员', sort: true, width: 300, align: 'center'}
            , {field: 'salesmanNameContract', title: '外销业务员', sort: true, width: 300, align: 'center'}
            , {field: 'totalContractAmount', title: '合同总额', sort: true, width: 170, align: 'center'}
            , {field: 'totalAmountUsd', title: '合同总额USD', sort: true, width: 170, align: 'center'}
            , {field: 'totalAmountRmb', title: '合同总额RMB', sort: true, width: 170, align: 'center'}
        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });

    /*table.on('tool(offertable)', function(obj){
        let data = obj.data;
        let id = data.id;
        if (obj.event === "quotationno"){
            parent.intab("views/jsp/ExportBusiness/tpl/viewexport.jsp?id="+id,"外销明细")
        }
    });*/


    form.on('submit(submitform)', function (data) {
        if (isEmpty(salesmanCodeCustomerList.getValue('valueStr')) && isEmpty(salesmanCodeContractList.getValue('valueStr'))  && isEmpty(deptSalesmanList.getValue('valueStr'))){
            data.field.salesmanCodeContract=user.code;
        }
        table.reload('offertableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        if (isEmpty(salesmanCodeCustomerList.getValue('valueStr')) && isEmpty(salesmanCodeContractList.getValue('valueStr'))  && isEmpty(deptSalesmanList.getValue('valueStr'))){
            queryReq.field.salesmanCodeContract=user.code;
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"exportContract/statistics/export/getContractCustomerInfo",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '客户订单总表.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });

    document.getElementById('clear').onclick = function(){
        salesmanCodeCustomerList.setValue([ ]);
        salesmanCodeContractList.setValue([ ]);
        customerTypeDataList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
    };
//字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});